import {getConfig, setConfig, updateConfig} from '@/mapper/config-store';

// 简单的UUID生成函数
function generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0;
        const v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// PLC地址存储服务
const plcAddressStore = {
    /**
     * 获取所有PLC地址
     * @returns {Promise<Array>} 地址列表
     */
    async getAll() {
        const addresses = await getConfig('plcAddresses') || [];
        return addresses;
    },

    /**
     * 根据ID获取PLC地址
     * @param {string} id 地址ID
     * @returns {Promise<Object|null>} 地址对象或null
     */
    async getById(id) {
        const addresses = await this.getAll();
        return addresses.find(addr => addr.id === id) || null;
    },

    /**
     * 添加新的PLC地址
     * @param {Object} addressData 地址数据
     * @returns {Promise<Object>} 添加后的地址对象
     */
    async add(addressData) {
        const addresses = await this.getAll();

        // 检查地址是否已存在
        const existingAddress = addresses.find(addr => addr.address === addressData.address);
        if (existingAddress) {
            throw new Error(`地址 ${addressData.address} 已存在`);
        }

        // 创建新地址对象
        const newAddress = {
            id: generateUUID(),
            address: addressData.address,
            station: addressData.station,
            category: addressData.category,
            type: addressData.type,
            description: addressData.description,
            propertyName: addressData.propertyName || ''
        };

        // 添加到列表并保存
        addresses.push(newAddress);
        await setConfig('plcAddresses', addresses);

        return newAddress;
    },

    /**
     * 更新PLC地址
     * @param {Object} addressData 地址数据
     * @returns {Promise<Object>} 更新后的地址对象
     */
    async update(addressData) {
        const addresses = await this.getAll();

        // 查找要更新的地址索引
        const index = addresses.findIndex(addr => addr.id === addressData.id);
        if (index === -1) {
            throw new Error(`未找到ID为 ${addressData.id} 的地址`);
        }

        // 检查地址是否与其他地址冲突
        const isDuplicate = addresses.some(addr =>
            addr.address === addressData.address && addr.id !== addressData.id
        );

        if (isDuplicate) {
            throw new Error(`地址 ${addressData.address} 已存在`);
        }

        // 更新地址
        const updatedAddress = {
            id: addresses[index].id,
            address: addressData.address,
            station: addressData.station,
            category: addressData.category,
            type: addressData.type,
            description: addressData.description,
            propertyName: addressData.propertyName || ''
        };

        addresses[index] = updatedAddress;
        await setConfig('plcAddresses', addresses);

        return updatedAddress;
    },

    /**
     * 删除PLC地址
     * @param {string} id 地址ID
     * @returns {Promise<boolean>} 是否删除成功
     */
    async delete(id) {
        const addresses = await this.getAll();
        const newAddresses = addresses.filter(addr => addr.id !== id);

        if (newAddresses.length === addresses.length) {
            throw new Error(`未找到ID为 ${id} 的地址`);
        }

        await setConfig('plcAddresses', newAddresses);
        return true;
    },

    async initDefaultValue() {
        const addresses = await this.getAll();
        if (addresses.length > 0) return;
        await setConfig("plcAddresses", [

            {
                "id": "1",
                "address": "MW8070",
                "station": "station1",
                "category": "realtime",
                "type": "float",
                "description": "左绕线张力",
                "propertyName": "LWT"
            },
            {
                "id": "2",
                "address": "MW8072",
                "station": "station1",
                "category": "realtime",
                "type": "int",
                "description": "左过线张力",
                "propertyName": "LTT"
            },
            {
                "id": "3",
                "address": "MW8074",
                "station": "station1",
                "category": "realtime",
                "type": "int",
                "description": "左挂钩张力",
                "propertyName": "LHT"
            },
            {
                "id": "4",
                "address": "MW8076",
                "station": "station1",
                "category": "realtime",
                "type": "int",
                "description": "左电阻值",
                "propertyName": "LRV"
            },
            {
                "id": "5",
                "address": "MW8080",
                "station": "station2",
                "category": "realtime",
                "type": "int",
                "description": "右绕线张力",
                "propertyName": "RWT"
            },
            {
                "id": "6",
                "address": "MW8082",
                "station": "station2",
                "category": "realtime",
                "type": "int",
                "description": "右过线张力",
                "propertyName": "RTT"
            },
            {
                "id": "7",
                "address": "MW8084",
                "station": "station2",
                "category": "realtime",
                "type": "int",
                "description": "右挂钩张力",
                "propertyName": "RHT"
            },
            {
                "id": "8",
                "address": "MW8086",
                "station": "station2",
                "category": "realtime",
                "type": "int",
                "description": "右电阻值",
                "propertyName": "RRV"
            },
            {
                "id": "9",
                "address": "MW8090",
                "station": "station1",
                "category": "realtime",
                "type": "int",
                "description": "左绕线速度",
                "propertyName": "LWS"
            },
            {
                "id": "10",
                "address": "MW8092",
                "station": "station2",
                "category": "realtime",
                "type": "int",
                "description": "右绕线速度",
                "propertyName": "RWS"
            },
            {
                "id": "11",
                "address": "MW8094",
                "station": "station1",
                "category": "realtime",
                "type": "int",
                "description": "左绕线圈数",
                "propertyName": "LWC"
            },
            {
                "id": "12",
                "address": "MW8096",
                "station": "station2",
                "category": "realtime",
                "type": "int",
                "description": "右绕线圈数",
                "propertyName": "RWC"
            }

        ]);
    }
};

export default plcAddressStore;
